package com.product.magina.wechatserver.utils;


import com.product.magina.wechatserver.constant.ProjectConst;
import com.product.magina.wechatserver.entity.AccessToken;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @desc 用户获取access_token,众号调用各接口时都需使用access_token
 **/
public class WeiXinUtils {
    /**
     * Get请求，方便到一个url接口来获取结果
     *
     * @param url
     * @return
     */
    public static JSONObject doGetStr(String url) {
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        JSONObject jsonObject = null;
        try {
            HttpResponse response = defaultHttpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "UTF-8");
                jsonObject = JSONObject.fromObject(result);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 获取access_token
     * @return
     */
    public static AccessToken getAccessToken(String projectAppId, String projectAppsecret){
        AccessToken accessToken = new AccessToken();
        String appid = projectAppId;
        //自己的配置APPSECRET;（公众号进行查阅）
        String appsecret = projectAppsecret;
        String url = ProjectConst.ACCESS_TOKEN_URL.replace("APPID" ,appid).replace("APPSECRET",appsecret);
        JSONObject jsonObject = doGetStr(url);
        if(jsonObject !=null){
            accessToken.setAccess_token(jsonObject.getString("access_token"));
            accessToken.setExpires_in(jsonObject.getLong("expires_in"));
        }
        return accessToken;
    }

    public static String authorizeUrl(String callbackUrl,String projectAppId){
        StringBuilder sb = new StringBuilder();
        try {
            sb.append("https://open.weixin.qq.com/connect/oauth2/authorize?appid=").
                    append(projectAppId).
                    append("&redirect_uri=").
                    append(URLEncoder.encode(callbackUrl,"UTF-8")).
                    append("&response_type=code").
                    //append("&scope=snsapi_base ").
                            append("&scope=snsapi_userinfo").
                    append("&state=STATE").
                    append("#wechat_redirect");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return sb.toString();
    }

}